import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:smart_shoes/define/define_colors.dart';
import 'package:smart_shoes/module/Login/view/login_view.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:smart_shoes/define/define_colors.dart';
import 'package:smart_shoes/manager/login_manager.dart';
import 'package:smart_shoes/models/message.dart';
import 'package:smart_shoes/router/app_router.dart';
import 'package:smart_shoes/tools/String_tool.dart';
import 'package:smart_shoes/tools/screen_tool.dart';
import 'package:smart_shoes/tools/style_tools.dart';
import 'package:smart_shoes/tools/toast_tools.dart';
import 'package:smart_shoes/tools/widget_tools.dart';

class LoginPage extends StatefulWidget {
  const LoginPage({super.key});

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  final _loginViewController = LoginViewController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: CustomColors.backgroundColor,
      body: SingleChildScrollView(
        child: GestureDetector(
          onTap: () {
            FocusScope.of(context).unfocus();
          },
          child: LoginViewController().contentView(),
        ),
      ),
    );
  }

  @override
  void dispose() {
    _loginViewController.dispose();
    super.dispose();
  }
}

enum LoginType { password, code, none }

class LoginViewController {
  var title = '密码登录'.obs;
  // 校验手机号
  var monitorCellPhoneNumbers = false.obs;
  // 新增手机号码输入框的控制器
  final phoneNumberController = TextEditingController();

  /// 获取验证码按钮文本
  String handleCodeText() =>
      countdownTime.value > 0 ? "${countdownTime.value}s" : "发送验证码";
  //记录手机号
  String phoneNumberStr = "";
  //记录验证码
  String codeStr = "";

  /// 定义一个定时器变量，用于控制验证码倒计时的计时操作
  Timer? _timer;
  // 将倒计时时间设置为 60 秒
  var countdownTime = 0.obs;
  var monitorVerificationpassword = false.obs;
  //记录密码
  String passwordStr = "";
  var issee = false.obs;
  var monitorVerificationCode = false.obs;
  final passwordController = TextEditingController();
  //记录是否是验证码初始化是0；方便判断；
  //1,为密码
  //2,为验证码
  var switchingAttempt = LoginType.none.obs;
  // 新增验证码输入框的控制器
  final codeController = TextEditingController();

  void dispose() {
    countdownTime.value = 0;
    _timer?.cancel();
  }

  /// 构建输入框边框样式，设置为无边框
  InputBorder buildInputBorder() {
    return InputBorder.none;
  }

  // ... 将原有LoginView类的所有内容移动到这里，类名改为LoginViewController ...
  // 包括所有变量和方法保持不变
  /// 对外内容视图接口
  Widget contentView() {
    //添加底纹Stack
    return Stack(
      children: [
        Positioned(
          top: 0,
          left: 0,
          child: Container(
            width: 107,
            height: 167,
            child: Image.asset(
              "assets/images/indexW.png",
              width: 15,
              height: 15,
            ),
          ),
        ),
        Positioned(
          left: ScreenTool.screenWidth - 107,
          bottom: ScreenTool.bottomSafeHeight,
          child: Container(
            width: 107,
            height: 167,
            child: Image.asset(
              "assets/images/indexS.png",
              width: 15,
              height: 15,
            ),
          ),
        ),
        _mainView(),
      ],
    );
  }

  /// 主内容视图
  Widget _mainView() {
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.only(top: 83),
      child: Column(
        children: [
          Image.asset('assets/images/logo.png', height: 49.5, width: 140),
          const SizedBox(height: 45.5),
          _inputView(),

          const SizedBox(height: 20),

          Obx(() {
            final loginType = switchingAttempt.value;
            if (loginType == LoginType.password ||
                loginType == LoginType.none) {
              title.value = "密码登录";
              return _inputPasswordView();
            } else {
              title.value = "验证码登录";
              return _inputCodeView();
            }
          }),
          const SizedBox(height: 20),
          // 使用 Align 组件让按钮右对齐
          Align(
            alignment: Alignment.centerRight,
            child: Obx(
              () => Container(
                padding: EdgeInsets.symmetric(horizontal: 24),
                child: WidgetTools().createCustomInkWellButton(
                  switchingAttempt.value == LoginType.code ? "密码登录" : "验证码登录",
                  () {
                    // final currentType = switchingAttempt.value;
                    WidgetsBinding.instance.addPostFrameCallback((_) {
                      switchingAttempt.value =
                          switchingAttempt.value == LoginType.code
                              ? LoginType.password
                              : LoginType.code;
                    });
                    // if (currentType == LoginType.none ||
                    //     currentType == LoginType.password) {
                    //   switchingAttempt.value = LoginType.code;

                    //   title.value = "密码登录";
                    // } else {
                    //   switchingAttempt.value = LoginType.password;
                    //   title.value = "验证码登录";
                    // }
                    codeController.clear();
                  },
                  bgColor: CustomColors.backgroundColor,
                  textColor: CustomColors.textColor,
                  buttonWidth: 90,
                  height: 17,
                  shadow: const BoxShadow(),
                ),
              ),
            ),
          ),
          const SizedBox(height: 69),
          WidgetTools().createMaterialButton(
            radius: 22,
            ScreenTool.screenWidth - 27 - 27,
            "登录",
            CustomColors.buttonColor,
            CustomColors.backgroundColor,
            0,
            () => _login(),
          ),

          const SizedBox(height: 16),

          //协议
          _agreement(),
          const SizedBox(height: 94.5),
          //第三方登录
          _thirdPartyLogin(),
        ],
      ),
    );
  }

  ///第三方登录
  Widget _thirdPartyLogin() {
    return Container(
      child: Column(
        children: [
          const Text(
            "其他登录方式",
            style: TextStyle(color: CustomColors.textColor, fontSize: 12),
          ),
          const SizedBox(height: 12),
          SizedBox(
            height: 40,
            width: 40,
            child: Image.asset(
              "assets/images/wachat.png",
              width: 15,
              height: 15,
            ),
          ),
        ],
      ),
    );
  }

  ///协议
  Widget _agreement() {
    // AssetImage(
    // "assets/images/wachatE.png")
    return Container(
      padding: const EdgeInsets.only(left: 27, right: 27),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          ///选择框
          GestureDetector(
            onTap: () {
              issee.value = !issee.value;
            },
            child: Obx(() {
              if (issee.value == false) {
                return Image.asset(
                  "assets/images/wachatE.png",
                  width: 15,
                  height: 15,
                );
              } else {
                return Image.asset(
                  "assets/images/wachatS.png",
                  width: 15,
                  height: 15,
                );
              }
            }),
          ),
          const SizedBox(width: 10),
          //协议文字
          Expanded(
            child: RichText(
              //您已阅读并同意《智慧鞋用户服务协议》《隐私权政策》《软件许可使用协议》
              text: const TextSpan(
                children: [
                  TextSpan(
                    text: "《智慧鞋用户服务协议》",
                    style: TextStyle(
                      color: CustomColors.buttonColor,
                      fontSize: 12.0,
                    ),
                  ),
                  TextSpan(
                    text: "《隐私权政策》",
                    style: TextStyle(
                      color: CustomColors.buttonColor,
                      fontSize: 12.0,
                    ),
                  ),
                  TextSpan(
                    text: "《软件许可使用协议》",
                    style: TextStyle(
                      color: CustomColors.buttonColor,
                      fontSize: 12.0,
                    ),
                  ),
                ],
                text: "您已阅读并同意",
                style: TextStyle(color: CustomColors.textColor, fontSize: 12.0),
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建通用输入框容器
  Widget buildInputContainer({required Widget child}) {
    return SizedBox(
      height: 48, //44
      child: Container(
        margin: const EdgeInsets.symmetric(horizontal: 27),
        padding: const EdgeInsets.symmetric(horizontal: 24),
        decoration: const BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.all(Radius.circular(22)),
        ),
        child: child,
      ),
    );
  }

  ///密码输入框
  Widget _inputPasswordView() {
    return buildInputContainer(
      child: Column(
        children: [
          Row(
            children: [
              const Text(
                "密码",
                style: TextStyle(color: CustomColors.textColor, fontSize: 14),
              ),
              const SizedBox(width: 12),
              Container(width: 0.5, height: 14, color: CustomColors.greyColor),
              const SizedBox(width: 12),
              Expanded(
                child: TextField(
                  controller: passwordController,
                  obscureText: true,
                  onChanged: (text) {
                    passwordStr = text;
                  },
                  decoration: InputDecoration(
                    // 所有状态下都设置为无边框
                    border: buildInputBorder(),
                    focusedBorder: buildInputBorder(),
                    enabledBorder: buildInputBorder(),
                    disabledBorder: buildInputBorder(),
                    errorBorder: buildInputBorder(),
                    hintText: "请输入密码",
                  ),
                ),
              ),
            ],
          ),
          Obx(() {
            if (monitorVerificationpassword.value == true) {
              return Container(
                padding: const EdgeInsets.only(left: 27),
                height: 44,
                child: _errorPrompt("请输入密码"),
              );
            }
            return Row();
          }),
        ],
      ),
    );
  }

  /// 验证码输入框
  /// 验证码输入框
  Widget _inputCodeView() {
    return buildInputContainer(
      child: Column(
        children: [
          Row(
            children: [
              const Text(
                "验证码",
                style: TextStyle(color: CustomColors.textColor, fontSize: 14),
              ),
              const SizedBox(width: 12),
              Container(width: 0.5, height: 14, color: CustomColors.greyColor),
              const SizedBox(width: 12),
              Expanded(
                child: TextField(
                  controller: codeController, // 使用控制器

                  textInputAction: TextInputAction.done,
                  onSubmitted: (text) {},
                  onChanged: (text) {
                    codeStr = text;
                  },
                  decoration: InputDecoration(
                    // 明确设置所有状态下的边框为无
                    border: buildInputBorder(),
                    focusedBorder: buildInputBorder(),
                    enabledBorder: buildInputBorder(),
                    disabledBorder: buildInputBorder(),
                    errorBorder: buildInputBorder(),
                    hintText: "请输入验证码",
                    suffixIcon: SizedBox(
                      height: 0,
                      child: GestureDetector(
                        // 根据倒计时状态决定是否可点击
                        onTap: () {
                          if (countdownTime.value == 0) {
                            countdownLogic();

                            print('Countdown started');
                            // 用于调试，确认点击事件是否触发
                            bool flg = StringTool.verifyPhoneNumber(
                              phoneNumberStr,
                            );
                            if (flg) {
                              ToastTools.showMessage("请输入有效手机号");
                              return;
                            }

                            var param = {"phone": phoneNumberStr};

                            LoginManager.loginCode(param, (Message message) {
                              print("LoginManager.loginCode");
                              print("=========strta==========");
                              print(message);
                            });
                          }
                        },
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Obx(
                              () => Text(
                                handleCodeText(),
                                style: TextStyle(
                                  fontSize: 13,
                                  color:
                                      countdownTime.value > 0
                                          ? CustomColors.greyColor.withOpacity(
                                            0.5,
                                          )
                                          : CustomColors.greyColor,
                                  // 倒计时期间文字颜色变浅
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ),
                ),
              ),
            ],
          ),
          Obx(() {
            if (monitorVerificationCode.value == true) {
              return Container(
                padding: const EdgeInsets.only(left: 27),
                height: 44,
                child: _errorPrompt("请输入验证码"),
              );
            }

            return Row();
          }),
        ],
      ),
    );
  }

  /// 验证码倒计时的逻辑处理方法
  /// 该方法会调用 startCountdown 方法启动倒计时，同时可以添加额外的逻辑，如验证手机号码格式
  void countdownLogic() {
    // 调用 startCountdown 方法启动倒计时
    startCountdown();
    // 可添加额外逻辑，如验证手机号码格式
  }

  /// 启动验证码倒计时的方法
  /// 该方法会将倒计时时间初始化为 60 秒，并启动一个每秒执行一次的定时器
  /// 定时器会每秒将倒计时时间减 1，直到倒计时时间为 0 时取消定时器
  void startCountdown() {
    // 将倒计时时间设置为 60 秒
    countdownTime.value = 60;
    // 创建一个每秒执行一次的定时器
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      // 检查倒计时时间是否大于 0
      if (countdownTime.value > 0) {
        // 若大于 0，则将倒计时时间减 1
        countdownTime.value--;
      } else {
        // 若等于 0，则取消定时器
        _timer?.cancel();
      }
    });
  }

  Widget _errorPrompt(String prompt) {
    return Row(
      children: [
        Image.asset("assets/images/wring.png", width: 15, height: 15),
        SizedBox(width: 5),
        Text(prompt, style: TextStyle(color: Colors.red, fontSize: 12)),
      ],
    );
  }

  _login() {
    // 校验逻辑
    _verify();
    if (issee.value == false) {
      Get.snackbar('提示', '请同意协议');
      return;
    }
    if (switchingAttempt.value == LoginType.code) {
      //验证码
      Map<String, dynamic> param = {"code": codeStr, "phone": phoneNumberStr};
      LoginManager.checkCode(param, (Message) {
        print(param);
        Get.toNamed(AppRoutes.home);
        countdownTime.value = 0;
        _timer?.cancel();
      });
    } else if (switchingAttempt.value == LoginType.password ||
        switchingAttempt.value == LoginType.none) {
      //密码
      Map<String, dynamic> param = {
        "password": passwordStr,
        "phone": phoneNumberStr,
      };
      LoginManager.passwordLogin(param, (Message m) {
        print(param);
        if (m.isSuccess == false) {
          ToastTools.showMessage(m.reason);
          return;
        } else {
          Get.toNamed(AppRoutes.home);
          countdownTime.value = 0;
          _timer?.cancel();
        }
      });
    }
  }

  // 校验逻辑
  _verify() {
    // 校验手机号
    monitorCellPhoneNumbers.value = false;
    monitorVerificationpassword.value = false;
    monitorVerificationCode.value = false;

    final phoneNumber = phoneNumberController.text.trim();

    // 简单的手机号格式校验，可根据实际需求调整
    if (!RegExp(r'^1[3-9]\d{9}$').hasMatch(phoneNumber) ||
        phoneNumber.isEmpty) {
      // Get.snackbar('提示', '请输入有效的手机号');
      monitorCellPhoneNumbers.value = true;
      return;
    }

    if (switchingAttempt.value == LoginType.none ||
        switchingAttempt.value == LoginType.password) {
      // 密码登录校验
      final password = passwordController.text.trim();
      if (password.isEmpty) {
        // Get.snackbar('提示', '请输入密码');
        monitorVerificationpassword.value = true;
        return;
      }
      // 简单的密码长度校验，可根据实际需求调整
      if (password.length < 6) {
        monitorVerificationpassword.value = true;
        return;
      }
    } else {
      // 验证码登录校验
      final code = codeController.text.trim();
      if (code.isEmpty) {
        // Get.snackbar('提示', '请输入验证码');
        monitorVerificationCode.value = true;
        return;
      }
      // 简单的验证码格式校验，可根据实际需求调整
      if (code.length != 6) {
        // Get.snackbar('提示', '验证码应为 6 位数字');
        monitorVerificationCode.value = true;
        return;
      }
    }

    // 校验用户是否同意协议
    if (issee.value == false) {
      Get.snackbar('提示', '请同意协议');
      return;
    }
    // Get.toNamed(AppRoutes.home);
    // countdownTime.value = 0;
    // _timer?.cancel();
  }

  /// 手机号码输入框
  Widget _inputView() {
    return Column(
      children: [
        buildInputContainer(
          child: Row(
            children: [
              const Text(
                "+86",
                style: TextStyle(color: CustomColors.textColor),
              ),
              const SizedBox(width: 12),
              Container(width: 0.5, height: 14, color: CustomColors.greyColor),
              const SizedBox(width: 12),
              Expanded(
                child: TextField(
                  controller: phoneNumberController, // 使用控制器
                  onChanged: (text) {
                    phoneNumberStr = text;
                  },
                  decoration: InputDecoration(
                    border: InputBorder.none,
                    focusedBorder: buildInputBorder(),
                    enabledBorder: buildInputBorder(),
                    disabledBorder: buildInputBorder(),
                    errorBorder: buildInputBorder(),
                    hintText: "请输入手机号",
                    contentPadding: EdgeInsets.zero,
                  ),
                ),
              ),
            ],
          ),
        ),
        Obx(() {
          if (monitorCellPhoneNumbers.value == true) {
            return Container(
              margin: const EdgeInsets.only(left: 27),
              height: 44,
              child: _errorPrompt("请输入有效手机号"),
            );
          }
          return Row();
        }),
      ],
    );
  }
}
